import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import 'package:ocr_plugin/ocr_rec_view.dart';
import 'package:ocr_plugin/ocr_rect_scanner_overlay_shape.dart';
import 'package:ocr_plugin_example/life_state.dart';

class OcrRectPage extends StatefulWidget {
  final String? filePath;
  final String? secondPath;

  const OcrRectPage({Key? key, this.filePath, this.secondPath}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _OcrRectPageState();
}

class _OcrRectPageState extends LifeState<OcrRectPage> {
  GlobalKey<OcrRecViewState> key = GlobalKey();
  GlobalKey _containerKey = GlobalKey();
  StreamSubscription? _streamSubscription;

  OcrRecViewController? pageController;
  Map? _backData;
  int _stateCount = 0;
  int _rectCount = 0;
  String? _message;
  String? usePath;
  bool destroy = false;

  final GlobalKey<OcrRecViewState> faceKey = GlobalKey();

  @override
  void initState() {
    usePath = widget.filePath;
    super.initState();
  }

  @override
  void dispose() {
    _streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        body: Container(
          key: _containerKey,
          width: double.infinity,
          height: double.infinity,
          // child: RotatedBox(
          //   //旋转横屏展示，90度：顺时针旋转四分之一圈的次数
          //   quarterTurns: 1,
          //   child: Stack(
          //     children: [ _rectWidget(),_back()],
          //   ),
          // ),
          child: Stack(
            children: [_rectWidget(),_back()],
          ),
        ),
      ),
    );
  }

  Widget _back() {
    return Container(
      margin: EdgeInsets.only(left: 15,right: 15, top: 45),
      child: Wrap(
        children: [

          _getBtn("返回", onPressed: () => Navigator.pop(context, _backData)),
          _getBtn("拍照", onPressed: () => pageController?.takePhotoCamera()),
          _getBtn("拍照截取区域", onPressed: () => pageController?.takePhotoCamera(isWithRect: true)),
          _getBtn("相册", onPressed: () => pageController?.takePhotoLibrary()),
          _getBtn("切换摄像头", onPressed: () => pageController?.switchCamera()),
          _getBtn("切换路径", onPressed: (){
            usePath = usePath == widget.filePath
                ? widget.secondPath
                : widget.filePath;
            print("-----------------usePath $usePath");
            pageController?.updateParams(ocrImgPath: usePath).whenComplete((){
              print("-----------------usePath111 $usePath");
              // Fluttertoast.showToast(msg: "切换路径完成");
            });
          }),
          if(_message != null || _rectCount > 0)
          Text("识别次数$_rectCount,$_message",style: TextStyle(color: Colors.white),)
        ],
      ),
    );
  }

  Widget _getBtn(String text,{VoidCallback? onPressed}){
    return TextButton(
        onPressed: () => onPressed?.call(),
        child: Text(
          text,
          style: TextStyle(color: Colors.white, fontSize: 18),
        ));
  }

  Widget _rectWidget() {
    Size s = MediaQuery.of(context).size;
    var height = max(s.width, s.height);
    var width = min(s.width, s.height);
    bool isPad = false;
    // var rect = Rect.fromLTRB(0,0,240*2,151*2);
    var rect = !isPad
        ? Rect.fromCenter(
        center: Offset(s.width / 2, s.height / 2),
        width: min(151 * 2, width),
        height: min(240 * 2, height))
        : Rect.fromCenter(
            center: Offset(s.width / 2, s.height / 2),
            width: min(240 * 2, height),
            height: min(151 * 2, width));
    // var rect = Rect.fromCenter(
    //     center: Offset(s.width / 2, s.height / 2),
    //     width: min(151 * 2, width),
    //     height: min(240 * 2, height));
    //身份证宽高 1.58:1
    print("MediaQuery size width ${s.width} height ${s.height} min $height");
    return SizedBox(
      // width: 240 * 2.5,
      // height: 151 * 2.5,
      child: OcrRecView(
        key: key,
        onOcrRectViewCreated: _created,
        ocrImgPath: widget.filePath,
        portraitToLandscape: !isPad,//true页面竖向时横向识别，false页面横向时横向识别
        type: 0,
        useTexture: true,
        overlay: OcrScannerOverlayShape(
            borderColor: pageController != null && pageController!.supportOcr ? Colors.white : Colors.red,
            borderRadius: 5,
          //绘制区域，对iOS无影响，对Android识别区有影响
            recognizeRect: rect),
        overlayMargin: EdgeInsets.fromLTRB(30, 15, 30, 15),
        faceKey: faceKey,
      )
    );
  }

  Widget faceWidget(){
    Size s = MediaQuery.of(context).size;
    var height = max(s.width, s.height);
    var width = min(s.width, s.height);
    //身份证宽高 1.58:1
    print("MediaQuery size width ${s.width} height ${s.height} min $height");

    var rect = Rect.fromCenter(
        center: Offset(s.width / 2, s.height / 2),
        width: min(151 * 2, width),
        height: min(240 * 2, height));

    // 必须使用padding，否则拿到的位置大小错误
    return Padding(padding: EdgeInsets.only(
        left: rect.center.dx -30, top: rect.bottom - 100 - 30),
      child: Container(
        key: faceKey,
        width: 110,
        height: 100,
        color: Colors.red,
      ),

    );

    return Container(
      key: faceKey,
      width: 110,
      height: 100,
      margin: EdgeInsets.only(
          left: rect.center.dx -30, top: rect.bottom - 100 - 30),
      color: Colors.red,
    );
  }

  void _created(OcrRecViewController controller) {
    pageController = controller;
    setState(() {});
    _streamSubscription =
        controller.scanUpdateController.stream.listen((event) {
      print("ocr rect view 识别成功---------------- ,is map ${event is Map}, recognized info : $event, destroy $destroy");
      if (event is Map) {
        if (event["message"] != null) {
          _message = event['message'];
          //包含报错信息
          print("ocr rect view error : ${event["message"]}");
          return;
        }
        _backData = event;
        _rectCount++;
        if(mounted) setState(() {});
        // Fluttertoast.showToast(msg: "识别成功----------------");
        //返回多次，导致pop两次出现黑屏，除了原生处理，这里也增加处理
        if(destroy != true){
          Navigator.pop(context, event);
          _streamSubscription?.cancel();
        }
        destroy = true;
      }
    });
  }

  @override
  void onResumed() {
    print("----------------------onResumed ${_stateCount++}");
    pageController?.resumeCamera();
  }

  @override
  void onPaused() {
    print("----------------------onPaused ${_stateCount++}");
    pageController?.pauseCamera();
  }


}
